<?php
namespace tools\controllers;

use yii\web\Controller;

// 转换接口
class ConvertapiController extends Controller
{
    public $layout = false;
    
    // php反序列化
    public function actionPhpunserialize()
    {
        $request = \Yii::$app->request;
        $content = $request->post("content", '');
        $data = array('jsonContent' => false, 'phpContent' => false);
        if (empty($content) || !is_string($content)) {
            echo json_encode($data);
            die();
        }
        $phpContent = @unserialize($content);
        if (empty($phpContent)) {
            // 错误的数据格式
            echo json_encode($data);
            die();
        }
        
        $data['jsonContent'] = json_encode($phpContent);
        $data['phpContent'] = $this->convert($phpContent);
        echo json_encode($data);
        die();
    }
    
    
    private function convert($content)
    {
        if (empty($content)) {
            return false;
        }
        
        $res = "";
        if (is_array($content)) {
            $res = $this->convertArray($content);
        } elseif (is_object($content)) {
            
        } elseif (is_string($content)) {
            $res = $this->convertString($content);
        } elseif (is_int($content)) {
            $res = $this->convertInt($content);
        }
        
        return $res;
    }
    
    private function convertArray($content)
    {
        $res = "array (\n";
        foreach ($content as $key => $value) {
            if (is_array($value)) {
                return $this->convertArray($value);
            } else {
                $res .= "    '{$key}' => '{$value}',\n";
            }
        }
        $res .= "),";
        return $res;
    }
    
    private function convertString($content)
    {
        $res = "'{$content}'";
        return $res;
    }
    
    private function convertInt($content)
    {
        $res = "{$content}";
        return $res;
    }
    
    private function convertObject($content)
    {
        
    }
}